package org.icedata.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.icedata.dao.UnitRepository;
import org.icedata.dto.Unit;
import org.icedata.dto.Word;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CourseController {
    private static final Logger logger = LogManager.getLogger(StaticController.class);
    private final UnitRepository unitRepository = UnitRepository.getInstance();

    @GetMapping("/units_info")
    public ResponseEntity<List<Map<String, String>> > getUnitsInfo() {
        logger.info("访问 /units_info");
        List<Unit> units = unitRepository.getAllUnits();
        List<Map<String, String>> unitInfoList = new ArrayList<>();

        for (Unit unit : units) {
            Map<String, String> unitInfo = new HashMap<>();
            unitInfo.put("unitName", unit.getUnitName());
            unitInfo.put("unitId", unit.getUnitId());
            unitInfoList.add(unitInfo);
        }
        return ResponseEntity.ok(unitInfoList);
    }

    @GetMapping("/get_unit_content")
    public ResponseEntity<List<Word>> getUnitContent(@RequestParam("unitId") String unitId) {
        logger.info("访问 /get_unit_content 参数unitId" + unitId);
        Unit selectedUnit = unitRepository.getUnitById(unitId);
        if (selectedUnit == null) {
            // 如果未找到匹配的单元，返回 404 - Not Found 状态码
            logger.info("访问 /get_unit_content 参数unitId" + unitId + " 不存在 响应404");
            return ResponseEntity.notFound().build();
        }

        // 获取单元内容
        List<Word> words = selectedUnit.getWords();
        return ResponseEntity.ok(words);
    }

}
